<template>
  <el-row>
    <el-col :span="24">
      <el-card>
        <el-form :inline="true">
          <el-form-item>
            <el-button type="primary" plain @click="addDialogShow=true">添加</el-button>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-input v-model="condition.name" placeholder="请输入要搜索的姓名" @input="selectByPage(1)"/>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-select
                v-model="condition.status"
                placeholder="请选择是否上架"
                style="width: 150px"
                clearable
                :value-on-clear="null"
                @change="selectByPage(1)"
            >
              <el-option label="上架" value="1"/>
              <el-option label="下架" value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-cascader
                v-model="condition.categoryId"
                placeholder="请选择分类"
                :options="allParent"
                clearable
                style="width: 130px"
                :value-on-clear="null"
                :props="props"
                @change="selectByPage(1)"
            />
          </el-form-item>
        </el-form>
        <el-table :data="pageInfo.list" border>
          <el-table-column prop="id" label="ID" width="50px"/>
          <el-table-column label="图片" width="70px" >
            <template #default="scope">
              <el-popover placement="right" trigger="hover" v-if="scope.row.picList.length > 0">
                <template #reference>
                  <el-image  style="width: 30px; height: 30px" :src="SERVER_ADDR + '/goods/pic/' + scope.row.picList[0].url" />
                </template>
                <el-image v-for="(pic,index) in scope.row.picList" :key="index" style="width: 50px; height: 50px; margin-right: 5px" :src="SERVER_ADDR + '/goods/pic/' +pic.url" :fit="fit" />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称"/>
          <el-table-column prop="dscp" label="描述"/>
          <el-table-column prop="price" label="售价" width="60px"/>
          <el-table-column prop="markPrice" label="标价" width="60px"/>
          <el-table-column prop="purchasePrice" label="进价" width="60px"/>
          <el-table-column prop="color" label="颜色" width="70px"/>
          <el-table-column prop="version" label="版本" width="70px"/>
          <el-table-column prop="count" label="数量" width="60px"/>
          <el-table-column prop="score" label="评分" width="60px"/>
          <el-table-column label="分类" width="100px">
            <template #default="scope">
              <el-text class="mx-1" type="primary" v-if="scope.row.category">{{ scope.row.category.name }}</el-text>
            </template>
          </el-table-column>
          <el-table-column label="是否推荐" width="90px" align="center">
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.recom == 1">推荐</el-tag>
              <el-tag type="info" v-if="scope.row.recom == 0">不推荐</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="是否上架" align="center" width="90px">
            <template #default="scope">
              <el-switch v-model="scope.row.status"
                         inline-prompt
                         :inactive-value="0"
                         :active-value="1"
                         style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                         inactive-text="下架"
                         active-text="上架"
                         @change="updateStatus(scope.row)"
              />

            </template>
          </el-table-column>

          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button size="small" plain type="success" @click="showDetailDialog(scope.row.id)">
                详情
              </el-button>
              <el-button size="small" plain type="warning" @click="selectById(scope.row.id)">
                修改
              </el-button>
              <el-button size="small" plain type="danger" @click="deleteGoods(scope.row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="row-bg" justify="center" style="margin-top: 20px;">
          <el-pagination layout="prev, pager, next" :total="pageInfo.total" :page-size="pageInfo.pageSize"
                         @change="selectByPage"/>
        </el-row>
      </el-card>
    </el-col>
  </el-row>

  <!-- 添加商品框开始 -->
  <el-dialog v-model="addDialogShow" title="添加商品" width="500">
    <el-form>
      <el-form-item label="图片" label-width="20%">
        <el-upload  v-model:file-list="goodsAdd.picList"
                    list-type="picture-card" :action="SERVER_ADDR +'/category/upload'" name="pic" :headers="headers"
                    :before-upload="beforePicUpload" :on-success="picUploadSuccess"
                      >
          <el-icon  class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="分类" label-width="20%">
        <el-cascader
            v-model="goodsAdd.categoryId"
            placeholder="请选择分类"
            :options="allParent"
            clearable
            style="width: 200px"
            :value-on-clear="null"
            :props="props"
        />
      </el-form-item>
      <el-form-item label="名称" label-width="20%">
        <el-input v-model="goodsAdd.name" placeholder="请输入名称" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="描述" label-width="20%">
        <el-input v-model="goodsAdd.dscp" placeholder="请输入描述" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="售价" label-width="20%">
        <el-input v-model="goodsAdd.price" placeholder="请输入售价" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="标价" label-width="20%">
        <el-input v-model="goodsAdd.markPrice" placeholder="请输入标价" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="进价" label-width="20%">
        <el-input v-model="goodsAdd.purchasePrice" placeholder="请输入进价" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="颜色" label-width="20%">
        <el-input v-model="goodsAdd.color" placeholder="请输入颜色" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="版本" label-width="20%">
        <el-input v-model="goodsAdd.version" placeholder="请输入版本" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="数量" label-width="20%">
        <el-input v-model="goodsAdd.count" placeholder="请输入数量" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="是否推荐" label-width="20%">
        <el-radio-group v-model="goodsAdd.recom">
          <el-radio label="不推荐" :value="0"/>
          <el-radio label="推荐" :value="1"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架" label-width="20%">
        <el-radio-group v-model="goodsAdd.status">
          <el-radio label="下架" :value="0"/>
          <el-radio label="上架" :value="1"/>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogShow = false">
          取消
        </el-button>
        <el-button type="primary" @click="insert">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加商品框结束 -->

  <!-- 修改商品框开始 -->
  <el-dialog v-model="updateDialogShow" title="修改商品" width="500">
    <el-form>
      <el-form-item label="图片" label-width="20%">
        <el-upload  v-model:file-list="goodsUpdate.picList"
                    list-type="picture-card" :action="SERVER_ADDR +'/category/upload'" name="pic" :headers="headers"
                    :before-upload="beforePicUpload" :on-success="picUploadSuccess"
        >
          <el-icon  class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="分类" label-width="20%">
        <el-cascader
            v-model="goodsUpdate.categoryId"
            placeholder="请选择分类"
            :options="allParent"
            clearable
            style="width: 200px"
            :value-on-clear="null"
            :props="props"
        />
      </el-form-item>
      <el-form-item label="名称" label-width="20%">
        <el-input v-model="goodsUpdate.name" placeholder="请输入名称" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="描述" label-width="20%">
        <el-input v-model="goodsUpdate.dscp" placeholder="请输入描述" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="售价" label-width="20%">
        <el-input v-model="goodsUpdate.price" placeholder="请输入售价" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="标价" label-width="20%">
        <el-input v-model="goodsUpdate.markPrice" placeholder="请输入标价" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="进价" label-width="20%">
        <el-input v-model="goodsUpdate.purchasePrice" placeholder="请输入进价" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="颜色" label-width="20%">
        <el-input v-model="goodsUpdate.color" placeholder="请输入颜色" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="版本" label-width="20%">
        <el-input v-model="goodsUpdate.version" placeholder="请输入版本" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="数量" label-width="20%">
        <el-input v-model="goodsUpdate.count" placeholder="请输入数量" autocomplete="off" style="width: 300px"/>
      </el-form-item>
      <el-form-item label="是否推荐" label-width="20%">
        <el-radio-group v-model="goodsUpdate.recom">
          <el-radio label="不推荐" :value="0"/>
          <el-radio label="推荐" :value="1"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架" label-width="20%">
        <el-radio-group v-model="goodsUpdate.status">
          <el-radio label="下架" :value="0"/>
          <el-radio label="上架" :value="1"/>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDialogShow = false">
          取消
        </el-button>
        <el-button type="primary" @click="update">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 修改商品框结束 -->

  <!-- 商品详情对话框开始 -->
  <el-dialog v-model="detailDialogShow" title="商品详情" >
    <div v-if="detailDialogShow" style="border: 1px solid #ccc">
      <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
      />
      <Editor
          style="height: 500px; overflow-y: hidden;"
          v-model="goodsUpdate.detail"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="detailDialogShow = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateDetail()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 商品详情对话框结束 -->
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import goodsApi from "@/api/goodsApi.js";
import {ref, shallowRef, onBeforeUnmount, computed} from "vue";
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import categoryApi from "@/api/categoryApi.js";
import {useTokenStore} from "@/stores/token.js";

const tokenStore = useTokenStore();
const headers = computed(() => {
  const token = tokenStore.tokenStr;
  return{
    token:token
  }
})

//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR)

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const mode = ref('default')
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容',
  MENU_CONF: {
    uploadImage: {
      server: `${SERVER_ADDR.value}/goods/upload`,
      fieldName: 'pic',
      headers: {
        token: tokenStore.tokenStr
      },
      customInsert(resp,insertFn) {
        //res 即服务端的返回结果
        let url = `${SERVER_ADDR.value}/goods/pic/${resp.data}`;
        //url - 图片通过后台访问的地址
        insertFn(url);
      }
    }
  }
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

//分页信息
const pageInfo = ref({
  pages: 0,
  pageSize: 0,
  pageNum: 0
});

//搜索条件
const condition = ref({
  name:null,
  categoryId:null,
  status:null
})
//父分类
const allParent = ref([])
//级联选择器配置选项
const props = {
  label:"name",
  value:"id",
  children:"childList",
  emitPath:false
}

//被添加商品信息
const goodsAdd = ref({
  id:null,
  name: null,
  dscp: null,
  detail: null,
  price: null,
  markPrice: null,
  purchasePrice: null,
  color:null,
  version:null,
  count:null,
  recom:1,
  categoryId:null,
  status:1,
  picList:[]
})
//是否显示添加对话框
const addDialogShow = ref(false);

//被修改商品信息
const goodsUpdate = ref({
  name: null,
  dscp: '',
  detail: '',
  price: null,
  markPrice: null,
  purchasePrice: null,
  color:null,
  version:null,
  count:null,
  recom:null,
  categoryId:null,
  status:null,
  picList:[]
})
//是否显示修改对话框
const updateDialogShow = ref(false);

//是否显示商品详情对话框
const detailDialogShow = ref(false);


//修改状态
function updateStatus(goods) {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  goodsApi.updateStatus(goods)
      .then(resp => {
        loading.close();
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1500
          })
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 1500
          });
        }
      });
}
//修改商品详情
function updateDetail(){
  //处理图片 realName -> url
  for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
    goodsUpdate.value.picList[i].url = goodsUpdate.value.picList[i].realName;
  }
  goodsApi.update(goodsUpdate.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1500
          })
          detailDialogShow.value = false;
          goodsUpdate.value = {
            id:null,
            name: null,
            dscp: '',
            detail: '',
            price: null,
            markPrice: null,
            purchasePrice: null,
            color:null,
            version:null,
            count:null,
            recom:null,
            categoryId:null,
            status:null,
            picList:[]
          };
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 1500
          });
        }
      })
}
//显示商品详情对话框
function showDetailDialog(id){
  goodsApi.selectById(id)
      .then(resp => {
        goodsUpdate.value = resp.data;
        //处理图片
        for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
          //保存图片真实名字
          goodsUpdate.value.picList[i].realName = goodsUpdate.value.picList[i].url;
          //回显图片
          goodsUpdate.value.picList[i].url = `${SERVER_ADDR.value}/goods/pic/${goodsUpdate.value.picList[i].url}`;
        }
        detailDialogShow.value = true;
      })

}
//修改
function update(){
  //处理图片 realName -> url
  for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
    goodsUpdate.value.picList[i].url = goodsUpdate.value.picList[i].realName;
  }
  goodsApi.update(goodsUpdate.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1500
          })
          updateDialogShow.value = false;
          goodsUpdate.value = {
            id:null,
            name: null,
            dscp: '',
            detail: '',
            price: null,
            markPrice: null,
            purchasePrice: null,
            color:null,
            version:null,
            count:null,
            recom:null,
            categoryId:null,
            status:null,
            picList:[]
          };
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 1500
          });
        }
      })
}

//根据id查询
function selectById(id){
  goodsApi.selectById(id)
      .then(resp => {
        goodsUpdate.value = resp.data;
        //处理图片
        for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
          //保存图片真实名字
          goodsUpdate.value.picList[i].realName = goodsUpdate.value.picList[i].url;
          //回显图片
          goodsUpdate.value.picList[i].url = `${SERVER_ADDR.value}/goods/pic/${goodsUpdate.value.picList[i].url}`;
        }
        updateDialogShow.value = true;
      })
}
//添加商品
function insert() {
  //处理图片 realName -> url
  for (let i = 0; i < goodsAdd.value.picList.length; i++) {
    goodsAdd.value.picList[i].url = goodsAdd.value.picList[i].realName;
  }
  const loading = ElLoading.service({
    lock: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  goodsApi.insert(goodsAdd.value)
      .then(resp => {
        loading.close();
        if (resp.code == 10000) {
          ElMessage({
            message: resp.msg,
            type: 'success',
            duration: 1500
          })
          addDialogShow.value = false;
          goodsAdd.value = {
            name: null,
            dscp: null,
            detail: null,
            price: null,
            markPrice: null,
            purchasePrice: null,
            color:null,
            version:null,
            count:null,
            recom:1,
            categoryId:null,
            status:1,
            picList:[]
          };
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage({
            message: resp.msg,
            type: 'error',
            duration: 1500
          });
        }
      });
}


//参数表示选中的图片
function beforePicUpload(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式有误')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2M!')
    return false
  }
  return true
}

//添加图片上传成功的回调
function picUploadSuccess(resp,uploadFile) { //resp - 服务器响应 uploadFile - 1.当前上传图片 2.和picList中对应的元素绑定
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    uploadFile.url = `${SERVER_ADDR.value}/goods/pic/${resp.data}`;
    uploadFile.realName = resp.data;
  } else {
    ElMessage.error(resp.msg);
  }
}
//删除
function deleteGoods(id) {
  ElMessageBox.confirm(
      '确认删除该商品吗?',
      '删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        goodsApi.delete(id)
            .then(resp => {
              if (resp.code == 10000) {
                ElMessage({
                  message: resp.msg,
                  type: 'success',
                  duration: 1500
                })
                selectByPage(pageInfo.value.pageNum);
              } else {
                ElMessage({
                  message: resp.msg,
                  type: 'error',
                  duration: 1500
                });
              }
            })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}

//分页搜索
function selectByPage(pageNum){
  const loading = ElLoading.service({
    lock: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  goodsApi.selectByPage(condition.value,pageNum,10)
      .then(resp => {
        loading.close();
        pageInfo.value = resp.data;
      });
}

//获取所有父分类
function selectAllParent() {
  categoryApi.selectAllParent()
      .then(resp => {
        allParent.value = resp.data;
      })
}

selectAllParent();
selectByPage(1);
</script>

<style scoped>

</style>